package com.yc.sakuralxm.uestcscanning.activity

import android.graphics.BitmapFactory
import android.os.Build
import android.os.Bundle
import android.support.annotation.RequiresApi
import android.view.View
import android.widget.ListView

import com.facebook.drawee.view.SimpleDraweeView
import com.yc.sakuralxm.uestcscanning.BaseActivity
import com.yc.sakuralxm.uestcscanning.R
import com.yc.sakuralxm.uestcscanning.adapters.ArrayAdapter
import com.yc.sakuralxm.uestcscanning.tools.*

import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream

import okhttp3.Call
import okhttp3.Callback
import okhttp3.Request
import okhttp3.Response

class ListImgActivity : BaseActivity() {
    private var listView: ListView? = null
    private var list = ListUtil.empty<String>()
    private val listIg = ListUtil.empty<String>()
    private var arrayAdapter: ArrayAdapter<String>? = null
    private val a = "http://prod20.yc-yunpass.com/uestc/jf/platform/wechart/pictureResponse?UUID="

    @RequiresApi(api = Build.VERSION_CODES.N)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_list_img)
        listView = findViewById(R.id.list) as ListView
        list = intent.getStringArrayListExtra("list")
        initData()

        //        list.forEach(str->{downLoadImg(list.get(0));
        //        });
        //        for (String s :list){
        //            downLoadImg(s.substring(2,s.length()-2));
        //        }
        list.forEach { s -> downLoadImg(s.substring(2, s.length - 2)) }

    }

    private fun downLoadImg(s: String) {
        val request = Request.Builder().url(s).build()
        OKhttpUtils.okHttpClient.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                runOnUiThread { L.e("下载失败") }
            }

            @Throws(IOException::class)
            override fun onResponse(call: Call, response: Response) {
                var inputS: InputStream? = null
                val buf = ByteArray(2048)
                var len = 0
                var fos: FileOutputStream? = null
                // 储存下载文件的目录
                val savePath = FilePathUtil.sdCardPath + s.substring(a.length) + ".jpg"

                try {
                    inputS = response.body().byteStream()
                    val total = response.body().contentLength()
                    val dir = File(FilePathUtil.sdCardPath)
                    if (!dir.exists())
                        dir.mkdirs()
                    val file = File(savePath)
                    fos = FileOutputStream(file)
                    var sum: Long = 0
                    len = inputS!!.read(buf);
                    while (len != -1) {
                        fos.write(buf, 0, len)
                        sum += len.toLong()
                        val progress = (sum * 1.0f / total * 100).toInt()
                        // 下载中
                    }
                    fos.flush()
                    runOnUiThread {
                        listIg.add(savePath)
                        arrayAdapter!!.notifyDataSetChanged()
                    }

                    L.e("路径" + savePath)
                    // 下载完成

                } catch (e: Exception) {
                    L.e(e.toString())
                } finally {
                    try {
                        if (inputS == null) {
                        } else {
                            inputS.close()
                        }
                    } catch (e: IOException) {
                    }

                    try {
                        if (fos != null)
                            fos.close()
                    } catch (e: IOException) {
                    }

                }
            }
        })
    }

    private fun initData() {

        // TODO  this will input message
        arrayAdapter = object : ArrayAdapter<String>(activity, R.layout.item_sdv, -1, listIg) {
            override fun loadViewData(view: View, position: Int, item: String) {
                super.loadViewData(view, position, item)
                val idSdv = view.findViewById(R.id.idSdv) as SimpleDraweeView
                val bitmap = BitmapFactory.decodeFile(listIg[position])
                idSdv.setImageBitmap(bitmap)
                //                idSdv.setImageURI("https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1511945266&di=eda66eb3ffdf0f331aca5c94494e9899&src=http://image.tianjimedia.com/uploadImages/2015/215/45/04L5VRR21C5W.jpg");

                //                ViewUtil.setImageURI(idSdv, "http://obmrnutvx.bkt.clouddn.com/android/3559/IMG_MODEL/1505198514320.png");
                idSdv.setOnClickListener { v -> IntentUtil.startActivity(activity, BigActivity::class.java, listIg[position]) }
                // TODO  this will input message
            }
        }

        listView!!.adapter = arrayAdapter
    }
}
